// pages/myself/order/orderDetails.js
var network = require('../../../utils/network_util.js');
var api = require('../../../utils/api.js');
var utils = require('../../../utils/utils.js');
var order = require('../../../template/orderTemp.js');
var Zan = require('../../../dist/index');
const app = getApp();

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    orderId: "",
    order: {

    },
    storeId: app.globalData.storeId,
    orderDate: 0,
    payDate: 0,
    payMonyDate: 0,
    hideStatus: true,
    flag: 0,
    allPrice: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "订单详情",
    })
    this.setData({
      orderId: options.orderId
    })
    network._post_json(this, api.getOrderDetails, { orderId: options.orderId }, success);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 取消订单
  cancel: function (e) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定取消该订单吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delOrder, { orderId: that.data.orderId }, cancelSuccess);

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  cancel01: function (e) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定删除该订单吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delOrder, { orderId: that.data.orderId }, cancelSuccess);

        } else if (res.cancel) {
          console.log('用户点击删除')
        }
      }
    })
  },

  // 确认收货
  endOrder: function (e) {
    network._post_json(this, api.endOrder, { orderId: this.data.orderId }, endSuccess);
  },

  // 购买
  pay: function (e) {
    var againPay = e.currentTarget.dataset.again; // 再次购标记
    // console.log(9999);
    // console.log(item);
    var products = this.data.order.product;
    var address = this.data.order.address;
    var liuyan = this.data.order.content;
    var newProducts = [];
    for (var i = 0; i < products.length; i++) {
      var product = {};
      product.id = products[i].id;
      product.title = products[i].title;
      product.smallImgUrl = products[i].smallImgUrl;
      product.count = products[i].count;
      //product.commodityActivity = products[i].commodityActivity;

      if (products[i].productSpec) {
        product.price = products[i].productSpec.price;
        product.specId = products[i].productSpec.id;
        product.specName = products[i].productSpec.name;
      } else {
        product.price = products[i].price;
      }
      newProducts.push(product);
    }
    try {
      wx.setStorageSync('products', newProducts)
    } catch (e) {
    }
    wx.redirectTo({
      url: '/pages/pay/pay?orderId=' + this.data.order.id + '&orderNO=' + this.data.order.orderNO + '&orderDesc=' + this.data.order.orderDesc + '&address=' + JSON.stringify(address) + '&liuyan=' + liuyan + '&againPay=' + againPay
    })
  },

  /**
  * 拨打电话
  */
  call: function (e) {
    /**
    * 获取商家电话
    */
    if (app.globalData.userAndTenantInfo) {
      wx.makePhoneCall({
        phoneNumber: app.globalData.userAndTenantInfo.tenant.phone
      })
    } else {
      app.userAndTenantInfoCallback = res => {
        this.setData({
          tenant: res.tenant
        })
      }
    }
  },

  //售后
  shouhouTk: function (e) {
    order.shouhouTk(1, e);
  },

  scan: function (e) {
    var orderId = e.currentTarget.dataset.id;
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        var scene = decodeURIComponent(res.path);
        console.log(scene)
        var index = scene.indexOf('scene=s=')
        // app.globalData.storeId == scene.substring(2, scene.length);
        network._post_json(this, api.end, { orderId: orderId, storeId: scene.substring(index + 8, scene.length) }, scanSuccess);
      }
    })
  },

  take: function (e) {
    var orderId = e.currentTarget.dataset.id;
    network._post_json(this, api.end, { orderId: orderId, storeId: this.data.storeId }, endSuccess);
  }
}))

// 获取订单详情结果
var success = function (that, res) {
  if (res.data.data) {
    var product = res.data.data.product;
    for (var i = 0; i < res.data.data.product.length; i++) {
      if (res.data.data.product[i].productSpec) {
        res.data.data.product[i].price = res.data.data.product[i].productSpec.price
      }
    }
    if (res.data.data.deliverDate!=null){
      res.data.data.deliverDate = utils.formatDate(new Date(res.data.data.deliverDate))
    }
    that.setData({
      order: res.data.data,
      orderDate: utils.formatDate(new Date(res.data.data.orderDate)),
      payDate: utils.formatDate(new Date(res.data.data.payDate)),
      payMonyDate: utils.formatDate(new Date(res.data.data.payMoneyDate)),
    })

    getTotal(that, res.data.data.product);
  }
}

var cancelSuccess = function (that, res) {
  //获取页面栈
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    prePage.onPullDownRefresh();
  }
  wx.navigateBack();
}
// 取消订单
var delSuccess = function (that, res) {
  that.showZanToast('订单取消成功');
}

// 完成订单
var endSuccess = function (that, res) {
  // if (res.data.data) {
  that.showZanToast('收货成功');
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    if (prePage.refresh && typeof (prePage.refresh) == "function") {
      prePage.refresh();
    }
  }
  setTimeout(function () {
    wx.navigateBack({

    })
  }, 2000)
  // }
}

var scanSuccess = function (that, res) {
  that.showZanToast('扫码成功');
  // that.data.order.status = 7
  // that.setData({
  //   order: that.data.order
  // })
  
  //获取页面栈
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    if (prePage.refresh && typeof (prePage.refresh) == "function") {
      prePage.refresh();
    }
  }
  setTimeout(function () {
    wx.navigateBack({

    })
  }, 2000)
  
}

/**
 * 商品总价
 */
var getTotal = function (that, items) {
  var price = 0;
  for (var i = 0; i < items.length; i++) {
    price += items[i].price * items[i].count
  }
  that.setData({
    allPrice: price
  })
  return price;
}